# coding=utf-8
from Database_Config import *
import tornado.ioloop
import tornado.web
import time
import datetime
import json
import sys
import os
import logging
from logging.handlers import RotatingFileHandler

reload(sys)
sys.setdefaultencoding('utf-8')

i = 0

def dictfetchall(cursor):
  columns = [col[0] for col in cursor.description]
  rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
  return rows

FILENAME = "logs/" + "ping" + ".log";
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format = FORMAT, filename = FILENAME, level = logging.DEBUG)
logging.getLogger('tornado.access').disabled = True
RotatingFileHandler(FILENAME, mode='a', maxBytes=1*1024*1024,
                     backupCount=1, encoding=None, delay=0)


if __name__ == "__main__":
    try:
        while True:
          c = conn_ibm_dbi.cursor()
          c.execute('select * from UACS_WEB_COMM')
          rows = dictfetchall(c)
          for row in rows:
              cmd = 'ping -c 1 -W 2 ' + row['IP']
              result = os.system(cmd)
              sql = "update UACS_WEB_COMM set REC_TIME = CURRENT_TIMESTAMP, PING_RESULT = '" + json.dumps(result) + "' where ID = '" + row['ID'] + "'"
              c.execute(sql)
              conn_ibm_dbi.commit()
          time.sleep(10)
    except Exception, ex:
        logging.error(ex) 
